package com.smart.campus.school.tcp;

import cn.hutool.http.HttpUtil;
import com.smart.campus.common.utils.DateUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Qualifier("serverHandler")
@Sharable
@Slf4j
public class ServerHandler extends ChannelInboundHandlerAdapter {
	@Autowired
	private TcpDataService tcpDataService;
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		log.info(">>>>>>>>>>>>>> netty接收到到客户端数据 :" + String.valueOf(msg));
		// #ACK 2015-05-09 08:14:08
		String date = DateUtils.getTime();
		String content = "#ACK "+date;
		log.info("响应给客户端数据:"+content);
		tcpDataService.sendDataToServer(String.valueOf(msg));
		ctx.writeAndFlush(content);
		//channelActive(ctx);//调用应答方法，应答数据帧
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		log.info("Channel is active\n");
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		log.info("\nChannel is disconnected");
		super.channelInactive(ctx);
	}

}
